package com.wuyou.dataStructure.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 前序遍历二叉树
 */
public class PreorderTraversal {

    public static void main(String[] args) {
        PreorderTraversal preorderTraversal = new PreorderTraversal();
        System.out.println();
    }



    public List<Integer> sol_1(TreeNode root){
        List<Integer> ans = new ArrayList<>();
        if (root != null) {
            preOrder(root, ans);
        }
        return ans;
    }

    public void preOrder(TreeNode root, List<Integer> ans){
        ans.add(root.val);
        if (root.left != null) {
            preOrder(root.left, ans);
        }
        if(root.right != null){
            preOrder(root.right, ans);
        }
    }

    public List<Integer> sol_2(TreeNode root){
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) {
            stack.push(root);
        }
        while (!stack.empty()) {
            TreeNode pop = stack.pop();
            ans.add(pop.val);
            if (pop.right != null) {
                stack.push(pop.right);
            }
            if (pop.left != null) {
                stack.push(pop.left);
            }
        }
        return ans;
    }
}
